package tech.yunjing.train.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import tech.yunjing.train.common.Constants;
import tech.yunjing.train.dao.UserInfoDao;
import tech.yunjing.train.entity.UserInfo;
import tech.yunjing.train.service.LoginRedisService;
import tech.yunjing.train.service.LoginService;
import tech.yunjing.train.service.exception.UserLoginException;
import tech.yunjing.train.util.Utils;

/**
 * purpose: 实现登录接口
 * Created by 吕祥 on 2017/6/11.
 */
@Service
public class LoginServiceImpl extends LoginRedisService implements LoginService, Constants {

    //注入的 UserInfoDao
    @Autowired
    UserInfoDao userInfoDao;

    //注入的 LoginRedisService
    @Autowired
    LoginRedisService<UserInfo> loginRedisService;

    /**
     * 用户登录保存信息
     * @param userAccount 用户账号
     * @param userPassword 用户密码
     * @return 是否成功提醒
     * @throws UserLoginException 登录异常
     */
    @Override
    public String userLoginSave(String userAccount, String userPassword) {
        if (userAccount == null || userAccount.trim().isEmpty()) {
            throw new UserLoginException("账号不能为空~！");
        }
        if (userPassword == null || userPassword.trim().isEmpty()) {
            throw new UserLoginException("密码不能为空~！");
        }

        //获取的密码MD5处理生成摘要对比
        String MdUserPassword = Utils.md5salt(userPassword);
        //依据手机号和密码查询
        Query queryUserInfo = new Query(Criteria.where("userAccount").is(userAccount).and("userPassword").is(MdUserPassword));
        //获得找到的对象
        UserInfo gainUser = userInfoDao.findOneUserInfo(queryUserInfo);
        if (gainUser == null) {
            throw new UserLoginException("账号或密码错误~！");
        }
        //用户已经删除(逻辑删除)
        if (gainUser.getStatus() == DEL_USERLOGIC_DELETE) {
            throw new UserLoginException("用户不存在~！");
        }

        //保存用户信息
        loginRedisService.userInfoPut(userAccount, gainUser,-1);

        return " 登录成功~！";
    }


    /**
     * 根据输入的账号得到用户信息对象
     * @param userAccount 用户账号
     * @return 用户信息对象
     */
    @Override
    public UserInfo getUserAccount(String userAccount) {

        if (userAccount == null || userAccount.trim().isEmpty()) {
            throw new UserLoginException("请输入账号");
        }
        //获得找到的用户信息对象
        UserInfo userInfo = loginRedisService.getUserAccountKey(userAccount);
        return userInfo;
    }

}
